#ifndef YCCOREUSERMANAGER_H
#define YCCOREUSERMANAGER_H
#include "user.h"
#include <QHash>
#include <QObject>

namespace yc {

class UserManager : public QObject
{
    Q_OBJECT

public:
    explicit UserManager(QObject* parent = nullptr) : QObject { parent } { }
    ~UserManager() { clear(); }

    bool contains(int id) const { return users_.contains(id); }
    User* getUser(int id) const { return users_.value(id); }
    User* addUser(int id)
    {
        if (!users_.contains(id)) {
            User* p = new User(id, QString(), this);
            users_.insert(id, p);
            return p;
        }
        return nullptr;
    }
    void clear()
    {
        for (auto it = users_.begin(), end = users_.end(); it != end; ++it) {
            delete it.value();
        }
        users_.clear();
    }

    void updateAvatarUrl(const QString& local_path)
    {
        QUrl url = QUrl::fromLocalFile(local_path);
        for (auto it = users_.begin(), end = users_.end(); it != end; ++it) {
            User* user = it.value();
            if (!user->avatarUrl().isValid() && local_path.contains(user->avatar())) {
                user->setAvatarUrl(url);
            }
        }
    }

private:
    QHash<int, User*> users_;
};

} // namespace yc

#endif // YCCOREUSERMANAGER_H
